﻿using MgSoft.Component;
using MgSoft.K3Cloud.WebApi.Dto;
using System;
using System.Collections.Generic;
using System.Text;
using Autofac;
using System.Reflection;
using System.Linq;
using System.Net.Http;

namespace MgSoft.K3Cloud.WebApi.DependenceInjection.Autofac
{
    public class ComponentWebApi : MgComponent
    {
        private Action<ApiServerInfo> cfgAction;

        public override void Register(object builder) => Register(builder, typeof(IApi).Assembly);

        public override void Register(object builder, Assembly assembly)
        {
            ContainerBuilder containerBuilder = builder as ContainerBuilder;
            if (containerBuilder == null) throw new ArgumentException("builder type must ContainerBuilder");

            Type basetype = typeof(IApi);
            containerBuilder.RegisterAssemblyTypes(assembly)
                .Where(t => basetype.IsAssignableFrom(t) && t.IsClass)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope()
                .PropertiesAutowired();

            containerBuilder.RegisterType<K3CloudApiExecuter>().SingleInstance().PropertiesAutowired();
            containerBuilder.RegisterType<K3CloudClientInfo>().SingleInstance().PropertiesAutowired();
            containerBuilder.RegisterType<KongdeeHttpClientHelper>().SingleInstance().PropertiesAutowired();
            containerBuilder.RegisterType<KingdeeClientInfoMemoryService>().SingleInstance().PropertiesAutowired();

            containerBuilder.RegisterType<ApiServerInfo>()
                .PropertiesAutowired()
                .OnActivating(p =>
                {
                    ApiServerInfo apiServerInfo = new ApiServerInfo();
                    cfgAction.Invoke(apiServerInfo);
                    p.ReplaceInstance(apiServerInfo);
                });

            //containerBuilder.RegisterType(this.GetType()).OnActivating(p => p.ReplaceInstance(this));
        }



        public void Config(Action<ApiServerInfo> cfg)
        {
            cfgAction = cfg;
        }
    }
}
